<template>
  <div class="public-container clearfix" ref="public-container">
    <div class="editor-head">
      <span>
        <router-link to="/">
          <span>《返回首页</span>
        </router-link>
      </span>
      <input class="head-title" v-model="title" type="text" placeholder="请输入标题" />
    </div>
    <div style="border: 1px solid #ccc;">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editor"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        style="height: 500px; overflow-y: hidden;"
        v-model="html"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="onCreated"
      />
    </div>
    <el-button type="warning" class="public-btn" @click="prePublic">发布文章</el-button>
    <el-dialog title="发布文章" :visible.sync="dialogVisible" width="60%" :before-close="handleClose">
      <el-tag size="large" type>简介</el-tag>
      <div>
        <input type="text" v-model="introduction" placeholder="请输入简介">
      </div>
      <el-tag size="large" type>封面</el-tag>
      <el-upload
        class="upload-blogface"
        drag
        action="http://localhost:3000/api/upload/blogfaceload"
        multiple
        :on-success="uploadSuccess"
        :on-error="uploadErr"
        :on-remove="handleRemove"
        :limit="1"
        :file-list="imgList"
        ref="upload"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
      </el-upload>
      <el-tag size="large" type>分类</el-tag>
      <el-select v-model="value" placeholder="请选择">
        <el-option
          v-for="item in options"
          :key="item.id"
          :label="item.categorize_name"
          :value="item.categorize_name"
        ></el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="surePublic()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
  
<script>
import Vue from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import {delBlogFaceApi , publicBlogApi} from '@/api/blog'
import {getCategorizes} from '@/api/categorize'
import userInfo from "../../../../store/user/userInfo";
export default Vue.extend({
  components: { Editor, Toolbar },
  data() {
    return {
      title: "",
      editor: null,
      html: "<p>hello</p>",
      // 简介
      introduction:'',
      toolbarConfig: {},
      editorConfig: { placeholder: "请输入内容..." },
      mode: "default", // or 'simple',
      dialogVisible: false,
      // 分类
      options: [
        {
          value: '选项1',
          label: '黄金糕'
        }
      ],
      value: "",
      imgList:[],
      imgUrl: "",
      filename:''
    };
  },
  mounted() {
    // 1.响应式内边距
    this.listenWidth();
    // 监听浏览器窗口变化
    window.onresize = () => {
      let w = document.body.clientWidth;
      if (w < 600) {
        return (() => {
          this.$refs["public-container"].style.padding = "10px";
        })();
      } else {
        return (() => {
          this.$refs["public-container"].style.padding = ".6rem 5rem .6rem 5em";
        })();
      }
    };
    // 模拟 ajax 请求，异步渲染编辑器
    setTimeout(() => {
      this.html = "<p>模拟 Ajax 异步设置内容 HTML</p>";
    }, 1500);

    // 请求分类数据
    this.getCategorizeSelect()
  },
  methods: {
    // 1.响应式内边距
    listenWidth() {
      let w = document.body.clientWidth;
      if (w < 500) {
        return (() => {
          this.$refs["public-container"].style.padding = "10px";
        })();
      } else {
        return (() => {
          this.$refs["public-container"].style.padding =
            "0.6rem 7.5rem 0.6rem 7.5rem ";
        })();
      }
    },
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },
    async getCategorizeSelect(){
      let data = {'pageSize':20,'pageNum':1}
      await getCategorizes(data).then(res=>{
        // 需要遍历数组修改数组数据
        this.options = res.data.categorizes
      }).catch(err=>{
        this.$message({
          type:'error',
          message:'获取分类失败'
        })
      })
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(async _ => {
          await this.delBlogFace()
          done();
        })
        .catch(_ => {});
    },
    // 博客封面上传成功
    uploadSuccess(response, file, fileList){
      if(response.code == 200){
        this.imgUrl = response.fileUrl
        this.filename = response.filename
      }else{
        this.$refs.upload.clearFiles()
        this.$message({
          type: 'error',
          message:response.msg
        })
      }
      
    },
    uploadErr(err, file, fileList){
    },
    async delBlogFace(){
      let data = {'filename':this.filename}
      await delBlogFaceApi(data).then(res=>{
        this.$refs.upload.clearFiles()
        this.imgUrl = ''
        this.filename = ''
      })
    },
    async handleRemove(file, fileList){
      await this.delBlogFace()
    },
    prePublic(){
      if(this.title == ''){
      this.$message({
          type: 'warning',
          message:'请输入标题'
        })
    }else if(this.html == ''){
      this.$message({
          type: 'warning',
          message:'请输入内容'
        })
    }else{
      this.dialogVisible = true
    }
    },
   async surePublic(){
      if(this.filename == ''){
      this.$message({
          type: 'warning',
          message:'请上传图片'
        })
    }else if(this.value == ''){
      this.$message({
          type: 'warning',
          message:'请选择分类'
        })
    }
    else if(this.introduction == ''){
      this.$message({
          type: 'warning',
          message:'请输入文章简介'
        })
    }else{
      // 确认发布
      const userInfo = JSON.parse(localStorage.getItem('userInfo'))
      if(!userInfo){
        return  this.$message({
          type: 'warning',
          message:'请先登录'
        })
      }
      const data = {
        'title':this.title,
        'introduction':this.introduction,
        'author':userInfo.username,
        'categorize':this.value,
        'content':this.html,
        'blogface':this.imgUrl
      }
      await publicBlogApi(data).then(res=>{
        this.dialogVisible = false
        this.title = ''
        this.$refs.upload.clearFiles()
        this.imgUrl = ''
        this.filename = ''
        this.value = ''
        this.html = ''
      }).catch(err=>{
        this.$message({
          type: 'error',
          message:err
        })
      })
    }

  },
  },
  
  beforeDestroy() {
    const editor = this.editor;
    if (editor == null) return;
    editor.destroy(); // 组件销毁时，及时销毁编辑器
  }
});
</script>
    
  <style lang="less" scoped>
.public-container {
  padding: 0.6rem 7.5rem 0.6rem 7.5rem;
  background-color: var(--bgColor);

  span {
    color: var(--font_2);
    font-size: 16px;
    router-link {
      color: var(--font_2);
    }
  }
  .editor-head {
    width: 100%;
    height: 50px;
    background-color: var(--cardColor);
    display: flex;
    align-items: center;
    span {
      cursor: pointer;
    }
    .head-title {
      width: 80%;
      height: 30px;
      background-color: var(--bgColor);
      outline: none;
      border: none;
      border-radius: 5px;
      margin-left: 10px;
      color: var(--font_2);
    }
  }
  .public-btn {
    float: right;
  }
}
.upload-blogface {
  margin-bottom: 20px;
}
</style>
<style src="@wangeditor/editor/dist/css/style.css"></style>